package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.entity.User;
import com.fzfnn.scrapbook.mapper.UserMapper;
import com.fzfnn.scrapbook.service.RadarService;
import com.fzfnn.scrapbook.util.R;
import com.fzfnn.scrapbook.vo.UserinformationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
public class RadarServiceImpl implements RadarService {


    @Autowired
    private RedisTemplate<String, String> redisMail;
    @Autowired
    private UserMapper userMapper;
    @Override
    public R findUsersInSameCity(String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息已失效，请重新登录");
        }

        String userTokenKey = "user:" + userId + ":loginInfo";
        if (!DataType.HASH.equals(redisMail.type(userTokenKey))) {
            return R.errorMsg("当前登录用户信息异常，请重新登录");
        }

        String city = (String) redisMail.opsForHash().get(userTokenKey, "city");
        if (city == null) {
            return R.errorMsg("未能获取当前城市信息");
        }

        // 核心优化：直接获取当前城市下的所有在线用户标记
        Set<String> cityOnlineKeys = redisMail.keys("city:online:" + city + ":*");
        if (cityOnlineKeys == null || cityOnlineKeys.isEmpty()) {
            return R.success("附近暂无用户", Collections.emptyList());
        }

        List<Integer> nearbyUserIds = new ArrayList<>();
        for (String key : cityOnlineKeys) {
            String[] parts = key.split(":");
            if (parts.length == 4) {
                String otherUserId = parts[3];
                if (!otherUserId.equals(userId)) {
                    nearbyUserIds.add(Integer.valueOf(otherUserId));
                }
            }
        }

        if (nearbyUserIds.isEmpty()) {
            return R.success("附近暂无用户", Collections.emptyList());
        }

        List<UserinformationVo> users = userMapper.selectUsersByIds(nearbyUserIds);
        return R.success("获取成功", users);
    }
}